import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import db from '@/utils/storage'

// 请求添加条件，如token
axios.interceptors.request.use(config => {
    const token = db.userLoc.get('TOKEN');
    if (token) {
        config.headers.token = 'Bearer ' + token;
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 接口返回处理
axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        return Promise.reject(error)
    }
)

function handleError(error, reject) {
    //   let isAlert = opts.custom ? opts.custom['isAlert'] : true;
    // isAlert = isAlert === undefined ? true : isAlert;
    if (error.response && error.response.data) {
        if (error.response.status === 500) {
            Message({
                message: error.response.data
            })
        }
    } else if (error.message) {
        Message({
            message: error.message
        })
    }
    reject(error)
}

function handleSuccess(res, resolve, opts) {
    const resData = res.data;
    if (resData.code === -201) {
        MessageBox.alert(resData.msg, '提醒', {
            confirmButtonText: '确定',
            callback: () => {
                // db.userLoc.clear();
                window.location.hash = '/login'
            }
        })
    }
    if (opts && opts.data && opts.data.back) {
        resolve(res)
    } else {
        resolve(resData)
    }

}

// http请求
const httpServer = (opts) => {
    // http默认配置
    const method = opts.method.toUpperCase()
    const httpDefaultOpts = {
        method,
        url: opts.url,
        // responseType: opts.responseType || '',
        // timeout: opts.custom && opts.custom['timeout'] || 30000
    }

    const dataRequest = ['PUT', 'POST', 'PATCH']
    if (dataRequest.includes(method)) {
        httpDefaultOpts.data = opts.data || {}
    } else {
        httpDefaultOpts.params = {
            ...(opts.data || {})
        }
    }

    // formData转换
    //   if (opts.formData) {
    //     httpDefaultOpts.transformRequest = [data => {
    //       const formData = new FormData()
    //       if (data) {
    //         Object.entries(data).forEach(item => {
    //           formData.append(item[0], item[1])
    //         })
    //       }
    //       return formData
    //     }]
    //   }

    const promise = new Promise((resolve, reject) => {
        axios(httpDefaultOpts).then(response => {
            handleSuccess(response, resolve, opts)
        }).catch(error => {
            handleError(error, reject, opts)
        })
    })
    return promise
}

export default httpServer
